#include <QHostAddress>
#include <QGridLayout>
#include <QVBoxLayout>
#include "login.h"
#include "qdebug.h"
#include <QFile>

Login::Login(QWidget *parent) : QDialog(parent)
{
    IP         = new QLabel("IP地址");
    input_IP   = new QLineEdit();
    Port       = new QLabel("端口号");
    input_Port = new QLineEdit();
    link       = new QPushButton("连接");
    socket     = new QTcpSocket();
    tcpserver  = new QTcpServer(this);
    tcpserver->listen(QHostAddress::Any,8888);
    link->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    this->setWindowTitle("五子棋联机版");
    initLayout();
    connect(tcpserver,&QTcpServer::newConnection,this,
                [=]()
    {
        QFile* file = new QFile("E:\\Qt\\Gobang\\info.txt");
        if(!file->open(QIODevice::WriteOnly|QIODevice::Truncate))
        {
            qDebug()<<"配置文件打开失败！";
            file->close();
            return;
        }
        QTextStream* stream = new QTextStream(file);
        socket=tcpserver->nextPendingConnection();
        (*stream) << socket->peerAddress().toString() << "\nServer";
        file->close();
        qDebug()<<"新的连接！";
        accept();
        this->close();
    });

    connect(link,&QPushButton::clicked,this,
            [=]()
    {
        QString IP  = input_IP->text();
        qint16 Port = input_Port->text().toInt();
        socket->connectToHost(QHostAddress(IP),Port);
        connect(socket,&QTcpSocket::connected,this,[=]()
        {
            QFile* file = new QFile("E:\\Qt\\Gobang\\info.txt");
            if(!file->open(QIODevice::WriteOnly|QIODevice::Truncate))
            {
                qDebug()<<"配置文件打开失败！";
                file->close();
                return;
            }
            QTextStream* stream = new QTextStream(file);
            (*stream) << IP << "\nClient";
            file->close();
            accept();
            this->close();
        });
    });


}
void Login::initLayout()
{
    QGridLayout* g = new QGridLayout();
    g->addWidget(IP,0,0,1,1);g->addWidget(input_IP,0,1,1,3);
    g->addWidget(Port,1,0,1,1);g->addWidget(input_Port,1,1,1,3);
    g->addWidget(link,0,4,2,2);
    this->setLayout(g);
}
